// JavaScript Document

/**
 * import compontent 
 */
Vsg.importClass(
	[
		"Vsg.DataSourceEntity.DataSourceEntityBuilder",
		"Vsg.EntityRecord.JobSchedule",
		"Vsg.EntityRecord.RunningJobSchedule",
		"Vsg.Component.SchedulerPanel",
		"Vsg.Component.TriggerPanel"
	]
);



/** ===============================
 * init ui interface 
 * ================================
 */
function init() {

	try {
		
		var $dsEntity = new Vsg.DataSourceEntity.DataSourceEntityBuilder();
		$dsEntity.setUrl( UrlMKey['job-schedule'] );
		$dsEntity.setEntityRecord( new Vsg.EntityRecord.JobSchedule() );	
		
		var $ds = $dsEntity.newLoadedDataSource({
			autoload:true
		});
		
		// ---- datasource entity -----
		var $runDsEntity = new Vsg.DataSourceEntity.DataSourceEntityBuilder();
		$runDsEntity.setUrl( UrlMKey['job-runningschedule']  );
		$runDsEntity.setEntityRecord( new Vsg.EntityRecord.RunningJobSchedule() );	
		
		var $runDs = $runDsEntity.newLoadedDataSource({
			autoload:true
		});

    	var expander = new Ext.ux.grid.RowExpander({
        	tpl : new Ext.Template(
            	'<b>工作类:</b> {jobClass}<br>',
            	'<b>描 述:</b> {description}'
        	)
    	});

		// --- defined the grid panel ---
    	var gridPanel = new Ext.grid.GridPanel({
			id:'avaiSchedulePanel',
        	width:700,
        	height:500,
        	store: $ds,
        	loadMask: true,
			plugins:expander,

        	// grid columns
			colModel:new Ext.grid.ColumnModel([
				expander,
				{
					id:"code",
					header: "调度任务编码",
					width: 80,
					sortable: true,
					dataIndex: "code"
				},
				{
					header: "调度任务名称",
					sortable: true, 
					dataIndex: "name"
				}				
			]),

        	// customize view config
        	viewConfig: {
            	forceFit:true
        	},
			
			tbar:[{
				id:"btnSchedule",
				text : "编制调度",
				iconCls :"time-add",
				xtype:"button",
				handler:Vsg.getDefinedEvent("job-schedule.evt_add")
			}],

        	// paging bar on the bottom
        	bbar: new Ext.PagingToolbar({
            	pageSize: Ext.PAGE_SIZE,
            	store: $ds,
            	emptyMsg: "当前没有数据",
            	items:[]
        	})
    	});
		
		// --- defined the grid panel ---
    	var gridPanel2 = new Ext.grid.GridPanel({
			id:'scheduledPanel',
        	width:250,
        	height:500,
        	store: $runDs,
        	loadMask: true,

        	// grid columns
			sm:new Ext.grid.RowSelectionModel({singleSelect:true}),
			colModel:new Ext.grid.ColumnModel([
				new Ext.grid.CheckboxSelectionModel() ,
				{
					id:"code",
					header: "调度任务编码",
					width: 25,
					sortable: true,
					dataIndex: "code"
				},
				{
					header: "调度任务名称",
					width: 25,
					sortable: true, 
					dataIndex: "name"
				},
				{
					header: "状态",
					width: 25,
					sortable: true,
					dataIndex: "status"
				
				},
				{
					header: "下次执行时间",
					width: 25,
					sortable: true,
					dataIndex: "nextExecTime"
				
				}				
			]),

        	// customize view config
        	viewConfig: {
            	forceFit:true
        	},
			
			tbar:[{
				id:"btnFlesh",
				text : "刷新",
				tip:"刷新新的应用",
				iconCls :"refresh",
				xtype:"button",
				handler:Vsg.getDefinedEvent("job-schedule.evt_refresh")
			},'-',{
				id:"btnStop",
				text : "停止",
				iconCls :"clock-stop",
				xtype:"button",
				handler:Vsg.getDefinedEvent("job-schedule.evt_stop")
			},'-',{
				id:"btnResume",
				text : "恢复",
				iconCls :"clock-start",
				xtype:"button",
				handler:Vsg.getDefinedEvent("job-schedule.evt_resume")
			},'-',{
				id:"btnRemove",
				text : "移除",
				iconCls :"time-delete",
				xtype:"button",
				handler:Vsg.getDefinedEvent("job-schedule.evt_delete")
			},'-',{
				id:"btnUpdateTrigger",
				text : "更新定时器",
				iconCls :"clock-edit",
				xtype:"button",
				handler:Vsg.getDefinedEvent("job-schedule.evt_updateTrigger")
			}],

        	// paging bar on the bottom
        	bbar: new Ext.PagingToolbar({
            	pageSize: Ext.PAGE_SIZE,
            	store: $ds,
            	displayInfo: true,
            	displayMsg: '显示当前列 {0} - {1} 共 {2}页',
            	emptyMsg: "当前没有数据",
            	items:[
                	'-', {
                	pressed: true,
                	enableToggle:true,
                	text: 'Show Preview',
                	cls: 'x-btn-text-icon details',
                	toggleHandler: function(btn, pressed){
                    	var view = grid.getView();
                    	view.showPreview = pressed;
                    	view.refresh();
                	}
            	}]
        	})
    	});		
	
	
		// --- show panel ---
		new Ext.Viewport({
			layout:"border",
			items:[{
				region:"center",
				border:false,
				margins:"5 0 5 5",
				layout:"fit",
				items:[gridPanel]
			}, {
				region:"east",
				border:false,
				width:"60%",
				split:true,
				margins:"5 5 5 0",
				layout:"fit",
				items:[gridPanel2]
			}]
		});
		
	} catch (e) {
		alert('出现系统性错误，请联系管理人员!');
		//Ext.log("Initial UI error: " + e);
	}

}
// --- run the init method
Vsg.run( init );



/** ==========================================
 * 	
 * 	place the code of event in following lines
 * 
 * ===========================================
 */
/**
 * 
 */
Vsg.definedEvent("job-schedule.evt_refresh" , function() {
	
	var scheduledPanel = Ext.getCmp("scheduledPanel");
		
	var ds  = scheduledPanel.getStore();
	try {
		ds.removeAll();
		ds.reload(); 
	} catch (e) {
		Ext.MessageBox.show({
           title: '错误提示',
           msg: '刷新列表窗口出错!',
           buttons: Ext.MessageBox.OK,
           icon: Ext.MessageBox.WARNING,
		   minWidth:260
       	});
	}	


});

Vsg.definedEvent("job-schedule.evt_stop" , function() {

	var scheduledPanel = Ext.getCmp("scheduledPanel");
	
	var selModel = scheduledPanel.getSelectionModel();
	var records = selModel.getSelections();
	
	// --- alert the message box
	if (records < 1) {
        Ext.MessageBox.show({
           title: '错误提示',
           msg: '请选择已编排的调度任务!',
           buttons: Ext.MessageBox.OK,
           icon: Ext.MessageBox.WARNING,
		   minWidth:260
       });
	   return;		
	}
	
	var triggerNames = [];
	var triggerGroups = [];
	for (var $i = 0 ; $i < records.length ; $i++) {
		triggerNames.push( records[$i].get('triggerName') );
		triggerGroups.push( records[$i].get('triggerGroup') );
	}	

	Ext.Ajax.request({
   		url: UrlMKey['job-stopschedule'],
  		success: function(response, opts) {

        	Ext.MessageBox.show({
          		title: '提示信息',
           		msg: '选择的调度任务已经停止!',
           		buttons: Ext.MessageBox.OK,
           		icon: Ext.MessageBox.INFO,
		   		minWidth:240
       		});

			var scheduledPanel = Ext.getCmp("scheduledPanel");
		
			var ds  = scheduledPanel.getStore();
			try {
				ds.removeAll();
				ds.reload(); 
			} catch (e) {
				Ext.MessageBox.show({
		           title: '错误提示',
		           msg: '刷新列表窗口出错!',
		           buttons: Ext.MessageBox.OK,
		           icon: Ext.MessageBox.WARNING,
				   minWidth:260
		       	});
			}	
			
		},
   		failure: function(response, opts) {
			
		},
   		params: { 'triggerNames': triggerNames , 'triggerGroups':triggerGroups }
	});


});


Vsg.definedEvent("job-schedule.evt_delete" , function() {

	var scheduledPanel = Ext.getCmp("scheduledPanel");
	
	var selModel = scheduledPanel.getSelectionModel();
	var records = selModel.getSelections();
	
	// --- alert the message box
	if (records < 1) {
        Ext.MessageBox.show({
           title: '错误提示',
           msg: '请选择已编排的调度任务!',
           buttons: Ext.MessageBox.OK,
           icon: Ext.MessageBox.WARNING,
		   minWidth:260
       });
	   return;		
	}

	var triggerNames = [];
	var triggerGroups = [];
	for (var $i = 0 ; $i < records.length ; $i++) {
		triggerNames.push( records[$i].get('triggerName') );
		triggerGroups.push( records[$i].get('triggerGroup') );
	}	

	Ext.Ajax.request({
   		url: UrlMKey['job-removeschedule'],
  		success: function(response, opts) {

        	Ext.MessageBox.show({
          		title: '提示信息',
           		msg: '选择的调度任务已经删除!',
           		buttons: Ext.MessageBox.OK,
           		icon: Ext.MessageBox.INFO,
		   		minWidth:240
       		});

			var scheduledPanel = Ext.getCmp("scheduledPanel");
		
			var ds  = scheduledPanel.getStore();
			try {
				ds.removeAll();
				ds.reload(); 
			} catch (e) {
				Ext.MessageBox.show({
		           title: '错误提示',
		           msg: '刷新列表窗口出错!',
		           buttons: Ext.MessageBox.OK,
		           icon: Ext.MessageBox.WARNING,
				   minWidth:260
		       	});
			}	
			
		},
   		failure: function(response, opts) {
			
		},
   		params: { 'triggerNames': triggerNames , 'triggerGroups':triggerGroups }
	});

});


Vsg.definedEvent("job-schedule.evt_resume" , function() {

	var scheduledPanel = Ext.getCmp("scheduledPanel");
	
	var selModel = scheduledPanel.getSelectionModel();
	var records = selModel.getSelections();
	
	// --- alert the message box
	if (records < 1) {
        Ext.MessageBox.show({
           title: '错误提示',
           msg: '请选择需要恢复的调度任务!',
           buttons: Ext.MessageBox.OK,
           icon: Ext.MessageBox.WARNING,
		   minWidth:260
       });
	   return;		
	}

	var triggerNames = [];
	var triggerGroups = [];
	for (var $i = 0 ; $i < records.length ; $i++) {
		triggerNames.push( records[$i].get('triggerName') );
		triggerGroups.push( records[$i].get('triggerGroup') );
	}	

	Ext.Ajax.request({
   		url: UrlMKey['job-resumeschedule'],
  		success: function(response, opts) {

        	Ext.MessageBox.show({
          		title: '提示信息',
           		msg: '选择的调度任务已经恢复!',
           		buttons: Ext.MessageBox.OK,
           		icon: Ext.MessageBox.INFO,
		   		minWidth:240
       		});

			var scheduledPanel = Ext.getCmp("scheduledPanel");
		
			var ds  = scheduledPanel.getStore();
			try {
				ds.removeAll();
				ds.reload(); 
			} catch (e) {
				Ext.MessageBox.show({
		           title: '错误提示',
		           msg: '刷新列表窗口出错!',
		           buttons: Ext.MessageBox.OK,
		           icon: Ext.MessageBox.WARNING,
				   minWidth:260
		       	});
			}	
			
		},
   		failure: function(response, opts) {
			
		},
   		params: { 'triggerNames': triggerNames , 'triggerGroups':triggerGroups }
	});

});

/**
 * handle event 
 */
Vsg.definedEvent("job-schedule.evt_add" , function() {

	var schedulePanel = Ext.getCmp("avaiSchedulePanel");
	
	var selModel = schedulePanel.getSelectionModel();
	var records = selModel.getSelections();
	// --- alert the message box
	if (records < 1) {
        Ext.MessageBox.show({
           title: '错误提示',
           msg: '请选择调度任务!',
           buttons: Ext.MessageBox.OK,
           icon: Ext.MessageBox.WARNING,
		   minWidth:180
       });
	   return;		
	}
	
	// ---- open in window  ----
	var win = null;

	try {
		// --- get the record ---
		var panel = new Vsg.Component.SchedulerPanel();
		if (!win) {
			win = new Ext.Window({
				layout:"fit",
				width:800,
				height:480,
				closeAction:"hide",
				title:"任务计划编排",
				items:[panel],
				modal:true,
				buttons:[
				{
					text:'保 存',
					handler:function() {
						try {
							// --- panel submit to response
							panel.submit({
								url:UrlMKey['job-addschedule'],
								success:function($form , $action) {
									// --- fire event ---
									try {
						
										// --- alert message ---
										var $result = $action.result;
        								Ext.MessageBox.show({
           									title: '提示信息',
           									msg: '任务编排已完成!',
           									buttons: Ext.MessageBox.OK,
           									icon: Ext.MessageBox.INFO,
		   									minWidth:240
       									});
										
										// reflash window 																
										var $dataSource  = Ext.getCmp("scheduledPanel").getStore();
										try {
											$dataSource.removeAll();
											$dataSource.reload(); 
										} catch (e) {
											
							
				        					Ext.MessageBox.show({
				           						title: '系统出错',
				           						msg: '"scheduledPanel"组件不能刷新!',
				           						buttons: Ext.MessageBox.OK,
				           						icon: Ext.MessageBox.ERROR,
						   						minWidth:240
				       						});											
											
										}
									} catch (ex) {
										// --- close the window
										alert(ex);
		
									}									
									if (win != null) {
										win.close();
									}																		 
								},
								failure:function() {
									// --- reponse error 	
								}
								
							})
							
						} catch (e) {
							
        					Ext.MessageBox.show({
           						title: '系统出错',
           						msg: '调度保存出错,请联系管理员!',
           						buttons: Ext.MessageBox.OK,
           						icon: Ext.MessageBox.ERROR,
		   						minWidth:240
       						});
														
						}
					}
				},
				{
					text:'关 闭',
					handler:function() {

						if (win != null) {
							win.close();
						}						
					}
				}
				],
				shadow:true,
				border:false
			});
		}
		win.show();
		
		
		// --- init default value ---
		panel.initValues( selModel.getSelected() );
	
	} catch (e) {
		alert(e);
	}

});

/**
 * 
 */
Vsg.definedEvent("job-schedule.evt_updateTrigger" , function() {

	var scheduledPanel = Ext.getCmp("scheduledPanel");
	
	var selModel = scheduledPanel.getSelectionModel();
	var records = selModel.getSelections();
	
	// --- alert the message box
	if (records < 1) {
        Ext.MessageBox.show({
           title: '错误提示',
           msg: '请选择已编排的调度任务!',
           buttons: Ext.MessageBox.OK,
           icon: Ext.MessageBox.WARNING,
		   minWidth:260
       });
	   return;		
	}
	
	// --- check job status if runnning or not
	var win = null;

	try {

		var panel = new Vsg.Component.TriggerPanel({
			margins:"5 5 5 0"
		});
		
		if (!win) {
			win = new Ext.Window({
				layout:"fit",
				width:440,
				height:470,
				closeAction:"hide",
				title:"更新触发器",
				items:[panel],
				buttons:[
				{
					text:'保 存',
					handler:function() {
						try {
							// --- panel submit to response
							panel.submit({
								url:UrlMKey['job-addschedule'],
								success:function() {
									// --- reponse success 
								},
								failure:function() {
									// --- reponse error 	
								}
								
							})
							
						} catch (e) {
							
        					Ext.MessageBox.show({
           						title: '系统出错',
           						msg: '调度保存出错,请联系管理员!',
           						buttons: Ext.MessageBox.OK,
           						icon: Ext.MessageBox.ERROR,
		   						minWidth:240
       						});
														
						}
					}
				},
				{
					text:'关 闭',
					handler:function() {

						if (win != null) {
							win.hide();
						}						
					}
				}
				],
				shadow:true,
				border:false
			});
			win.show();
			
		}
	
	} catch (e) {
		alert(e);
	}	

});
